package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.PreloadDeviceAndApp;
import com.letv.whatslive.model.convert.PreloadDeviceAndAppConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/4/29.
 */
@Repository
public class PreloadDeviceAndAppDAO extends BaseDAO{
    protected String collectionName = "preloadDeviceAndApp";

    private static final Logger logger = LoggerFactory.getLogger(PreloadDeviceAndAppDAO.class);

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public Long saveOrUpdate(PreloadDeviceAndApp preloadDeviceAndApp) {
        DBObject query = new BasicDBObject("_id", preloadDeviceAndApp.getId());
        DBObject dbo = this.dbCollection.findOne(query);
        if (dbo == null) {
            if(preloadDeviceAndApp.getId()==null)
                preloadDeviceAndApp.setId(getAutoIncrementId());
            dbo = PreloadDeviceAndAppConvert.castPreloadDeviceAndAppToDBObject(preloadDeviceAndApp);
            if (dbo != null) {
                this.dbCollection.save(dbo);
                return ObjUtils.toLong(dbo.get("_id"));
            }
        } else {
            DBObject update = new BasicDBObject();

            if(preloadDeviceAndApp.getDeviceId()!=null){
                update.put("deviceId",preloadDeviceAndApp.getDeviceId());
            }

            if((preloadDeviceAndApp.getAppId()!=null)) {
                update.put("appId",preloadDeviceAndApp.getAppId());
            }

            if((preloadDeviceAndApp.getSysType()!=null)) {
                update.put("sysType",preloadDeviceAndApp.getSysType());
            }

            if((preloadDeviceAndApp.getSysVersion()!=null)) {
                update.put("sysVersion",preloadDeviceAndApp.getSysVersion());
            }
            this.dbCollection.update(query, new BasicDBObject("$set", update), false, false);
            return preloadDeviceAndApp.getId();
        }

        return 0L;
    }

    /**
     * 根据查询条件查询所有的应用
     * @param params
     * @param start
     * @param limit
     * @return
     */
    public List<PreloadDeviceAndApp> getPreloadDeviceAndAppListByParams(Map<String, Object> params, Integer start, Integer limit) {
        List<PreloadDeviceAndApp> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                PreloadDeviceAndApp preloadDeviceAndApp = PreloadDeviceAndAppConvert.castDBObjectToPreloadDeviceAndApp(dbObject);
                result.add(preloadDeviceAndApp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据查询条件Map获取查询条件对象
     * @param params
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("appId") != null) {
                query.put("appId", ObjectUtils.toLong(params.get("appId")));
            }
            if (params.get("deviceId") != null) {
                query.put("deviceId", ObjectUtils.toLong(params.get("deviceId")));
            }
            if (params.get("appIdIn") != null) {
                List<Long> lAppIds = (List<Long>) params.get("appIdIn");
                BasicDBList values = new BasicDBList();
                if(!(lAppIds==null||lAppIds.isEmpty())){
                    for(Long appId:lAppIds){
                        values.add(appId);
                    }
                    query.put("appId", new BasicDBObject("$in", values));
                }
            }
            if (params.get("deviceIdIn") != null) {
                List<Long> lDeviceIds = (List<Long>) params.get("deviceIdIn");
                BasicDBList values = new BasicDBList();
                if(!(lDeviceIds==null||lDeviceIds.isEmpty())){
                    for(Long deviceId:lDeviceIds){
                        values.add(deviceId);
                    }
                    query.put("deviceId", new BasicDBObject("$in", values));
                }
            }

            if (params.get("sysType") != null) {
                query.put("sysType", ObjectUtils.toInteger(params.get("sysType")));
            }
            if (params.get("sysVersion") != null) {
                query.put("sysVersion", ObjectUtils.toString(params.get("sysVersion")));
            }
        }

        return query;
    }


    /**
     * 根据条件获取相应的应用白名单列表
     * @param params
     * @return
     */
    public List<PreloadDeviceAndApp> getAllPreloadDeviceAndAppByParams(Map<String, Object> params){
        List<PreloadDeviceAndApp> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                PreloadDeviceAndApp preloadDeviceAndApp = PreloadDeviceAndAppConvert.castDBObjectToPreloadDeviceAndApp(dbObject);
                result.add(preloadDeviceAndApp);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据设备Id获取应用
     * @param id
     * @return
     */
    public PreloadDeviceAndApp getPreloadDeviceAndAppById(Long id) {
        BasicDBObject query = new BasicDBObject();
        PreloadDeviceAndApp preloadDeviceAndApp = new PreloadDeviceAndApp();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            preloadDeviceAndApp = PreloadDeviceAndAppConvert.castDBObjectToPreloadDeviceAndApp(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return preloadDeviceAndApp;
    }

    public PreloadDeviceAndApp savePreloadDeviceAndApp(PreloadDeviceAndApp preloadDeviceAndApp) {
        try {
            preloadDeviceAndApp.setId(getAutoIncrementId());
            DBObject dbo = PreloadDeviceAndAppConvert.castPreloadDeviceAndAppToDBObject(preloadDeviceAndApp);
            WriteResult wr = this.dbCollection.insert(dbo);
            return preloadDeviceAndApp;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    public Long countPreloadDeviceAndAppByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    public void deletePreloadDeviceAndAppByParams(Long id){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);
        this.dbCollection.remove(query);
    }

    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("_id", -1);
        }
        return order;
    }

    public List<PreloadDeviceAndApp> getPreloadDeviceAndAppByParams(Map<String, Object> params, Map<String, Object> orders) {

        List<PreloadDeviceAndApp> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                result.add(PreloadDeviceAndAppConvert.castDBObjectToPreloadDeviceAndApp(dbObject));
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }


    public List<PreloadDeviceAndApp> getPreloadDeviceAndAppListByParams(Map<String, Object> orders, Map<String, Object> params, Integer start, Integer limit) {

        List<PreloadDeviceAndApp> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip)
                    .sort(order).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                PreloadDeviceAndApp preloadDeviceAndApp = PreloadDeviceAndAppConvert.castDBObjectToPreloadDeviceAndApp(dbObject);
                result.add(preloadDeviceAndApp);
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }
}
